package com.army.study.provider;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;

import java.util.List;

/**
 * 列表组件提供者
 */
public abstract class ListComponentProvider<T> extends BaseItemProvider {
    protected Context context;

    // 列表项数据
    protected List<T> listBean;
    // 布局资源Id
    protected int resourceId;

    /**
     * 列表组件提供者构造方法
     * @param context
     * @param listBean
     * @param resourceId
     */
    public ListComponentProvider(Context context, List<T> listBean, int resourceId) {
        this.context = context;
        this.listBean = listBean;
        this.resourceId = resourceId;
    }

    /**
     * 列表项绑定抽象方法
     * @param componentViewHolder
     * @param item
     * @param position
     */
    protected abstract void onItemDataBind(ComponentViewHolder componentViewHolder, T item, int position);

    @Override
    public int getCount() {
        return listBean.size();
    }

    @Override
    public T getItem(int i) {
        return listBean.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ComponentViewHolder viewHolder;
        if (component == null) {
            // 根据资源Id，获取到布局组件
            component = LayoutScatter.getInstance(context).parse(resourceId, null, false);
            // 初始化组件视图缓存类
            viewHolder = new ComponentViewHolder(component);
            // 设置组件标签为缓存视图
            component.setTag(viewHolder);
        } else {
            // 直接从组件标签获取到组件视图缓存类
            viewHolder = (ComponentViewHolder) component.getTag();
        }
        if (viewHolder != null) {
            // 获取列表项数据
            T item = listBean.get(i);

            // 设置数据到列表项绑定
            onItemDataBind(viewHolder, item, i);

            // 设备数据列表项事件
            viewHolder.getComponentView()
                    .setClickedListener(componentView -> onItemClick(componentView, item, i));
        }
        return component;
    }

    /**
     * 绑定Item项的事件，此方法需要实现子类来实现逻辑
     * @param component
     * @param item
     * @param position
     */
    protected void onItemClick(Component component, T item, int position) {
    }
}
